package com.gupt.reggie.service.impl;/*
@author name
@data 2023/4/19-17:58
*/


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gupt.reggie.common.CustomException;
import com.gupt.reggie.dto.DishDto;
import com.gupt.reggie.entity.Category;
import com.gupt.reggie.entity.Dish;
import com.gupt.reggie.entity.DishFlavor;
import com.gupt.reggie.mapper.DishMapper;
import com.gupt.reggie.service.CategoryService;
import com.gupt.reggie.service.DishFlavorService;
import com.gupt.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@Transactional  //操作多个表： 保证事务一致性
public class DishServiceImpl extends ServiceImpl<DishMapper,Dish> implements DishService {
    @Autowired
    @Lazy  //循环bean的注入，延迟bean加载
    private CategoryService categoryService;

    @Autowired
    DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Page page(int page, int pageSize, String name) {

        //创建分页器
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.like(name != null,Dish::getName,name);  //查询具体值
        queryWrapper.orderByDesc(Dish::getUpdateTime);   //排序

        //执行
        pageInfo = this.page(pageInfo);

        //对象拷贝:忽略属性名为records的值
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        //自行处理records值：为dish内容
        List<Dish> records = pageInfo.getRecords();


        //将List<Dish> 赋给 List<DishDto>
        List<DishDto> list = records.stream().map((item) ->{
            DishDto dishDto = new DishDto();
            //由于对象是new出来的，其他属性无赋值，使用需手动赋值
            //对象赋值
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                dishDto.setCategoryName(category.getName()); //查询后赋值给dishDto对象
            }
            return dishDto;
        }).collect(Collectors.toList());

        dishDtoPage.setRecords(list);

        return dishDtoPage;
    }

    /**
     * 新增菜品，保证对应口味数据
     * @param dishDto
     */
    @CacheEvict(value = "DishCache",allEntries = true)  //菜品添加，删除所有缓存数据
    @Override
    public void saveWithFlavor(DishDto dishDto) {

        //保存基本信息到dish表
        this.save(dishDto);

        Long dishId = dishDto.getId();

//      StreamAPI 处理
//        List<DishFlavor> flavors = dishDto.getFlavors();
//        flavors = flavors.stream().map((item) ->{
//            log.info("添加菜品每个口味为：{}",item.toString());
//            item.setDishId(dishId);
//            return item;  // 返回值
//        }).collect(Collectors.toList());

        List<DishFlavor> flavors = dishDto.getFlavors();
        //保存菜品口味到菜品口味表dish_flavor
        // 因dishDto无直接封装口味表dish_flavor中 dishId的值 即无法保存该值，需手动注入
        flavors = flavors.stream()
                .filter(item -> item.getName() != "" && item.getValue() != "")
                .peek(item -> item.setDishId(dishId))
                .collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors); //批量插入值 底层：一个一个save
    }

    /**
     * 查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品基本信息 表：dish
        Dish dish = this.getById(id);

        //对象拷贝
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);

        //查询菜品口味信息 表：dish_flavor
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());

        List<DishFlavor> list = dishFlavorService.list(queryWrapper);
        //将没有拷贝到的flavors手动注入
        dishDto.setFlavors(list);
        return dishDto;
    }

    @Override
    @Transactional  //多张表操作：事务一致性
    public void updateWithFlavor(DishDto dishDto) {
        //更新菜品表dish基本信息
        this.updateById(dishDto);

        //更新口味表dish_flavor的信息  思路：删除当前口味，添加新的当前口味
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);

        //添加新的当前口味
        List<DishFlavor> flavors = dishDto.getFlavors();


//        flavors = flavors.stream().map((item) ->{
//            item.setDishId(dishDto.getId());
//            return item;  // 返回值
//        }).collect(Collectors.toList());
/*
        stream流api，将 flavors 列表转换为一个流，
        使用filter过滤器，对过滤后的元素进行操作
        peek 方法主要用于调试或副作用操作 设置dishId的值
        collect 将处理后的元素收集到一个新的列表中 后赋值给本身(覆盖
        stream 是处理指定的元素，最后返回这些元素组成的新列表
 */


        //dish_flavor表的dishId需要手动注入 因为DishDto中的DishId前端并没有直接传值
        flavors = flavors.stream()
                .filter(item -> item.getName() != "" && item.getValue() != "")
                .peek(item -> item.setDishId(dishDto.getId()))
                .collect(Collectors.toList());

        dishFlavorService.saveBatch(flavors);
    }


    @Override
    public void deleteDishById(List<Long> ids) {

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId,ids);
        queryWrapper.eq(Dish::getStatus,1);
        int count = this.count(queryWrapper);
        if(count > 0){
            //无法删除，则抛出异常
            throw new CustomException("菜品正在售卖，不能删除");
        }

        //删除菜品
        boolean remove1 = this.removeByIds(ids);
        //删除口味
        LambdaQueryWrapper<DishFlavor> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(DishFlavor::getDishId,ids);
        boolean remove2 = dishFlavorService.remove(wrapper);
        if(!remove1 || !remove2){
            throw new CustomException("删除异常");
        }
    }

    @Cacheable(value = "DishCache" ,key = "#dish.categoryId + '_' + #dish.getStatus()")//由查询条件组成key值
    @Override
    public List<DishDto> list(Dish dish) {

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //排序
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        //添加状态为1（起售）的商品
        queryWrapper.eq(Dish::getStatus,1);

        List<Dish> list = this.list(queryWrapper);

        //将List<Dish> 赋给 List<DishDto>

        List<DishDto> dishDtoList = list.stream().map((item) ->{
            DishDto dishDto = new DishDto();
            //由于对象是new出来的，其他属性无赋值，使用需手动赋值
            //对象赋值
            BeanUtils.copyProperties(item,dishDto);

            Long categoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if(category != null){
                dishDto.setCategoryName(category.getName()); //查询后赋值给dishDto对象
            }
            //查询当前菜品id
            Long id = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper();
            lambdaQueryWrapper.eq(DishFlavor::getDishId,id);
            //select * form dish_flavor where dish_Id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        return dishDtoList;
    }
}
